package com.app.web.user
import com.app.cache.SessionHandler
import com.app.constant.CommonConstant
import com.app.model.TUser
import com.app.model.wrapper.JsonResultWrapper
import com.app.model.wrapper.MessageDefined
import com.app.service.system.IFunctionService
import com.app.service.user.IUserService
import com.app.web.BaseAction
import com.frame.verify.Require
import com.frame.verify.annotation.Chain
import com.frame.verify.annotation.Param
import com.frame.verify.annotation.ParamVerify
import groovy.transform.CompileStatic
import groovy.transform.TypeChecked
import org.apache.shiro.SecurityUtils
import org.apache.shiro.authz.annotation.RequiresPermissions
import org.apache.shiro.authz.annotation.RequiresUser
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Component

import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse
import javax.ws.rs.*
import javax.ws.rs.core.Context
import javax.ws.rs.core.MediaType
/**
 * 用户action
 * Created by three on 14-7-29.
 * com.app.web.user
 * User: 王利平
 */
@Component
@CompileStatic
@TypeChecked
@Path("/user")
class UserAction extends BaseAction {

    @Autowired
    private IUserService userService;
    @Autowired
    private IFunctionService functionService;

    /**
     * 用户登录登录认证请求
     * @param request
     * @param response
     * @return
     */
    @Path("/login")
    @POST
    @Produces(MediaType.APPLICATION_JSON)
    login(
          @Context HttpServletRequest request,@Context HttpServletResponse response) {
        if(SecurityUtils.getSubject().isAuthenticated())
            [code:'0000', msg: '登录成功', result: SessionHandler.user()];
        else{
            def loginError=request.getAttribute("loginError")
            def result="";
            String loginException=loginError.toString();
            if(loginException.contains("CaptchaShiroException"))
                result="验证码错误"
            else if(loginException.contains("PasswordShiroException")||loginException.contains("UserNameShiroException"))
                result="用户名或者密码错误"
            else
                result="未知错误，请联系管理员"
            [code:'9999', msg: '登录失败', result:result];
        }
    }

    @Path("/logout")
    @Produces(MediaType.APPLICATION_JSON)
    @POST
    @RequiresUser
    logout(
          @Context HttpServletRequest request,@Context HttpServletResponse response) {
        SecurityUtils.getSubject().logout()
        [code:'0000', msg: '退出成功', result: ''];
    }

    /**
     * 查询用户列表
     */
    @Path("/")
    @GET
    @Produces(MediaType.APPLICATION_JSON)
    @RequiresPermissions("user:read")
    list(@Context HttpServletRequest request,
         @QueryParam("name")String name,
         @QueryParam("pwd")String pwd ) {
        CommonParams commonParams = getCommonParams(request);

        def param = [:];
        param << [
                name:name,
                pwd:pwd
        ];

        def res = userService.findListPageByParams(param, commonParams.order, commonParams.pageNo, commonParams.iDisplayLength)

        res;
    }

    /**
     * 新增用户
     */
    @Path("/")
    @POST
    @Produces(MediaType.APPLICATION_JSON)
    @RequiresPermissions("user:write")
    @ParamVerify(params = [
            @Param(name = "name", chain=[@Chain(cls=Require.class)]),
            @Param(name = "pwd", chain=[@Chain(cls=Require.class)])
    ])
    add(@FormParam("name") @DefaultValue("") String name, @FormParam("pwd") @DefaultValue("") String pwd) {
        if(''==name || ''==pwd) {
            return [code:'0001', msg: '用户名或密码不能未空', result: null];
        }
        // 其他有效性检查
        Long userId = (Long)userService.addBasic(new TUser(name: name, pwd: pwd));
        [code:'0000', msg: '新增用户成功', result: [userId: userId]];
    }

    /**
     * 查询用户详情
     * @param userId
     */
    @Path("/{userId}")
    @GET
    @Produces(MediaType.APPLICATION_JSON)
    @RequiresPermissions("user:detail")
    detail(@PathParam("userId") Long userId) {
        [code:'0000', msg: '得到用户详情成功', result: userService.findObjByKey(userId)];
    }

    /**
     * 更新用户
     */
    @Path("/{userId}")
    @PUT
    @Produces(MediaType.APPLICATION_JSON)
    @RequiresPermissions("user:update")
    update(@PathParam("userId") Long userId, @BeanParam TUser user) {
        user.id = userId
        try{
            userService.modifyBasic(user)
            new JsonResultWrapper<Map>('0000', '更新用户成功', [userId: user.id]);
        } catch(Exception  e) {
            e.printStackTrace()
            new JsonResultWrapper<Map>('0009', '更新用户失败', [userId: user.id]);
        }


    }

    /**
     * 删除用户
     */
    @Path("/{userId}")
    @DELETE
    @Produces(MediaType.APPLICATION_JSON)
    @RequiresPermissions("user:delete")
    delete(@PathParam("userId") Long userId) {
        try{
            userService.delBasic(new TUser(id: userId));
            new JsonResultWrapper<Map>('0000',  '删除用户成功', [userId: userId]);
        } catch(Exception e) {
            new JsonResultWrapper<String>('0001',  '删除用户失败', e.getMessage());
        }


    }

    /**
     * 得到用户菜单
     */
    @Path("/menu/enable")
    @GET
    @Produces(MediaType.APPLICATION_JSON)
    @RequiresUser
    userMenu(@PathParam("userId") String userId) {
        def params = [:];
        params << [isActive:CommonConstant.IsActive.TRUE.getValue()];

        def menuList = functionService.findListByParams(params, null);

        return MessageDefined.SUCCESS.wrapper(menuList);
    }

}
